<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户" prop="params.nickName">
        <el-input v-model="queryParams.params.nickName" placeholder="请输入用户" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="类别" prop="categoryId">
        <el-tree-select v-model="queryParams.categoryId" :data="categoryOptions" check-strictly
          :render-after-expand="false" style="width: 240px" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="queryParams.content" placeholder="请输入发表的内容" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择内容状态" clearable>
          <el-option v-for="dict in campus_content_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择内容类型" clearable>
          <el-option v-for="dict in campus_content_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="匿名" prop="isAnonymous">
        <el-select v-model="queryParams.isAnonymous" placeholder="请选择是否匿名" clearable>
          <el-option v-for="dict in campus_anonymous" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['campus:content:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['campus:content:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['campus:content:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column label="用户" align="center" prop="params.nickName" />
      <el-table-column label="类别" align="center" prop="params.categoryName" />
      <el-table-column label="内容" align="center" prop="content" show-overflow-tooltip />
      <el-table-column label="内容状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="campus_content_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="内容类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="campus_content_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="点赞数量" align="center" prop="loveCount" />
      <el-table-column label="是否匿名" align="center" prop="isAnonymous">
        <template #default="scope">
          <dict-tag :options="campus_anonymous" :value="scope.row.isAnonymous" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130px">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['campus:content:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['campus:content:remove']">删除</el-button>
          <el-button link type="primary" icon="el-icon-view" @click="handleInfo(scope.row)"
            v-hasPermi="['campus:content:query']">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改内容管理对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="contentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入发布内容的用户ID" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="类别" prop="categoryId">
          <el-tree-select v-model="form.categoryId" :data="categoryOptions" :render-after-expand="false" check-strictly
            style="width: 240px" />
        </el-form-item>
        <el-form-item label="内容">
          <editor ref="editorRef" v-model="form.content" :min-height="160" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择内容的状态">
            <el-option v-for="dict in campus_content_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择内容的类型">
            <el-option v-for="dict in campus_content_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!-- 根据类型显示图片上传组件 -->
        <el-form-item v-if="form.type === 1" label="上传图片">
          <image-upload v-model="form.fileList" />
        </el-form-item>
        <!-- 根据类型显示视频上传组件 -->
        <el-form-item v-if="form.type === 2" label="上传视频">
          <FileUpload v-model="form.fileList" :fileSize="500" :fileType="['mp4', 'avi', 'mkv', 'mov', 'flv']"
            :isShowTip="true" />
        </el-form-item>
        <el-form-item label="是否匿名" prop="isAnonymous">
          <el-select v-model="form.isAnonymous" placeholder="请选择是否匿名">
            <el-option v-for="dict in campus_anonymous" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 调度校园墙内容详细 -->
    <el-dialog title="调度内容详细" v-model="showInfo" width="700px" append-to-body>
      <el-form :model="form" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="头像：">
              <image-preview :src="form.params.avatar"> </image-preview>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户昵称：">{{
              form.params.nickName
              }}</el-form-item>
            <el-form-item label="用户账户：">{{
              form.params.userName
              }}</el-form-item>
            <el-form-item label="标签：">
              <li v-for="item in form.tags">{{ item.tagName }}</li>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="分类：">{{
              form.params.categoryName
              }}</el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="内容：" style="white-space: pre-wrap">
              {{ form.content }}
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="form.type == 1">
            <el-form-item label="图片：">
              <div class="picture_container">
                <div class="picture_item" v-for="(item, key) in form.fileList" :key="key">
                  <image-preview class="image-preview" :src="item"></image-preview>
                </div>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="form.type == 2">
            <el-form-item label="视频：">
              <div class="video_item" v-for="(item, key) in form.fileList" :key="key">
                <video controls :src="handleUrl(item)"
                  style="width: 85%; max-width: 640px; margin-bottom: 10px;"></video>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showInfo = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup name="Content">
import { listContent, getContent, delContent, addContent, updateContent } from "@/api/campus/content";
import { isExternal } from '@/utils/validate';
import { loadAllParams } from "@/api/page";
import { loadCategoryOptions } from "../../../api/campus/campus";



const { proxy } = getCurrentInstance();
const { campus_content_status, campus_anonymous, campus_content_type } = proxy.useDict('campus_content_status', 'campus_anonymous', 'campus_content_type');

const contentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 定义一个 ref 来获取富文本编辑器的实例
const editorRef = ref(null);
//是否显示详细的弹出层
const showInfo = ref(false);

const data = reactive({
  form: {
    fileList: [] // 初始化为空数组
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    params: {
      nickName: null,
    },
    categoryId: null,
    content: null,
    status: null,
    type: null,
    isAnonymous: null,
    createUser: null,
    updateUser: null
  },
  rules: {
    categoryId: [
      { required: true, message: "分类不能为空", trigger: "blur" },
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "类型不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


/** 查询内容管理列表 */
function getList() {
  loading.value = true;
  listContent(queryParams.value).then(response => {
    contentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


/** 查询下拉树结构类别信息 */
const categoryOptions = ref([]);
const getCategoryOptions = async () => {
  try {
    categoryOptions.value = await loadCategoryOptions(loadAllParams);
  } catch (error) {
    console.error('加载分类数据失败:', error);
  }
}


function handleUrl(url) {
  // 检查输入是否为空或不是字符串
  if (!url || typeof url !== 'string') {
    console.warn('无效的URL提供:', url);
    return '';
  }

  try {
    // 使用isExternal方法检查URL是否为外部链接
    if (isExternal(url)) {
      return url;
    }

    // 确保基础API路径以斜杠结尾
    const basePath = import.meta.env.VITE_APP_BASE_API.endsWith('/')
      ? import.meta.env.VITE_APP_BASE_API
      : import.meta.env.VITE_APP_BASE_API + '/';

    // 确保url不以斜杠开头，避免重复斜杠
    url = url.startsWith('/') ? url.slice(1) : url;

    // 返回拼接后的完整路径
    return basePath + url;
  } catch (error) {
    // 捕获并记录处理URL时可能出现的错误
    console.error('处理URL时出错:', error);
    return '';
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    contentId: null,
    userId: null,
    categoryId: null,
    content: "<p></p>",
    status: null,
    type: null,
    fileCount: null,
    loveCount: null,
    isAnonymous: null,
    remark: null,
    delFlag: null,
    createTime: null,
    createUser: null,
    updateTime: null,
    updateUser: null
  };
  proxy.resetForm("contentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.contentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加内容管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _contentId = row.contentId || ids.value
  getContent(_contentId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改内容管理";
  });
}

/** 详细按钮操作 */
function handleInfo(row) {
  const _id = row.contentId;
  getContent(_id).then(response => {
    form.value = response.data;
    console.log(form.value);
    showInfo.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["contentRef"].validate(valid => {
    if (valid) {
      // 去除 <p> 标签
      form.value.content = form.value.content.replace(/<p>|<\/p>/g, '');
      if (form.value.contentId != null) {
        updateContent(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addContent(form.value).then(response => {
          console.log(form.value)
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _contentIds = row.contentId || ids.value;
  proxy.$modal.confirm('是否确认删除内容管理编号为"' + _contentIds + '"的数据项？').then(function () {
    return delContent(_contentIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

getList();
getCategoryOptions();
</script>

<style lang="scss" scoped>
.picture_container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  /* 每行显示四个图片 */
  gap: 10px;
  /* 图片之间的间距 */
}

.picture_item {
  /* 不需要设置固定宽度 */
}

.image-preview {
  border-radius: 10px;
  width: 100%;
  aspect-ratio: 1/1;
}

.video_item {
  display: block;
  /* 确保每个 video_item 是块级元素 */
  margin-bottom: 10px;
  /* 可选：添加间距 */
}
</style>
